<template>
  <page-layout>
    <a-card>
      <a-button size="large" @click="$router.go(-1)">返回</a-button>
      <a-form
        style="margin-top: 36px"
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="部门">
          <a-select
            placeholder="请选择部门"
            size="large"
            v-decorator="[
              'department_id',
              { rules: [{ required: true, message: '请选择部门!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[0]"
              :key="item.department_id"
              :value="item.department_id"
            >
              {{ item.name }}
            </a-select-option>
        
          </a-select>
        </a-form-item>
        <a-form-item label="需求名称" required>
          <a-input
            placeholder="请输入需求名称"
            size="large"
            v-decorator="[
              'title',
              {
                rules: [{ required: true, message: '请输入需求名称!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="需求方">
          <a-select
            placeholder="请选择需求方负责人"
            size="large"
            v-decorator="[
              'author_id',
              { rules: [{ required: true, message: '请选择需求方负责人!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[1]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审核方">
          <a-select
            placeholder="请选择审核方负责人"
            size="large"
            v-decorator="[
              'examiner_id',
              { rules: [{ required: true, message: '请选择审核方负责人!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[4]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联项目">
          <a-select
            placeholder="请选择关联项目"
            size="large"
            v-decorator="[
              'project_id',
              { rules: [{ required: false, message: '请选择关联项目!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[2]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联产品">
          <a-select
            placeholder="请选择关联产品"
            size="large"
            v-decorator="[
              'produce_id',
              { rules: [{ required: false, message: '请选择关联产品!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[3]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="需求详情">
          <EditorBar v-decorator="['description']" :isClear="isClear" />
        </a-form-item>
        <a-form-item label="附件">
          <a-upload-dragger
            v-decorator="[
              'files',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile
              }
            ]"
            name="file"
            :multiple="false"
            action="/commons/qiniu_uploadFile"
            @change="handleChange"
            :beforeUpload="beforeUpload"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" style="color: #dddddd" />
            </p>
            <!-- <p class="ant-upload-text">点击或者拖拽文件来上传你的附件</p> -->
            <p class="ant-upload-hint" style="color: #ccc">
              点击或者拖拽文件来上传附件
            </p>
          </a-upload-dragger>
        </a-form-item>
        <!-- <a-form-item label="抄送">
          <a-button
            type="primary"
            :ghost="true"
            size="large"
            style="width: 80px"
          >
            <a-icon type="plus" style="color: #0097e0"></a-icon
          ></a-button>
          <a-button
            type="primary"
            :ghost="true"
            size="large"
            style="width: 80px; margin-left: 20px"
          >
            <a-icon type="plus" style="color: #0097e0"></a-icon
          ></a-button>
        </a-form-item> -->

        <a-form-item :wrapper-col="{ span: 12, offset: 10 }">
          <a-button type="primary" size="large" @click="handleSubmit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-layout>
</template>

<script>
import { add, detail, edit } from "@/services/demand";
import { getDepartmentList } from "@/services/department";
import { getProjectList } from "@/services/projects";
import { getUsersList,getTechnologyManager } from "@/services/user";
import { getProducelist } from "@/services/produce";
import PageLayout from "@/layouts/PageLayout";
import EditorBar from "@/components/wangEditor";
import Cookie from "js-cookie";
// import moment from "moment";
export default {
  name: "demand",
  components: { PageLayout, EditorBar },
  data() {
    this.form = this.$form.createForm(this);
    return {
      nameId:Cookie.get("name"),
      isClear: false,
      detail: "",
      selectDatas: [],
      editData: {}
    };
  },
  created() {
    //获取cookie中的数据
    let userInfo = JSON.parse(window.localStorage.getItem('admin.user'))
  
    // 如果时编辑过来
    if (this.$route.query.id) {
      Promise.all([
        detail(this.$route.query.id),
        getDepartmentList(),
        getUsersList(),
        getProjectList(),
        getProducelist() ,
        getTechnologyManager()
      ]).then((arr) => {
        const editData = arr.splice(0, 1);
        this.editData = editData[0].data.data;
        for (let key in this.form.getFieldsValue()) {
          // console.log(key);
          if (key === "author_id") {
            // console.log(moment(editData[key]), "moment(editData[key])");
            this.form.setFieldsValue({
              [key]: this.editData.author.id
            });
            continue;
          }
          if (key === "files") {
            // console.log(moment(editData[key]), "moment(editData[key])");
            this.form.setFieldsValue({
              [key]:
                this.editData.files instanceof Array ? this.editData.files : []
            });
            continue;
          }
          this.form.setFieldsValue({ [key]: this.editData[key] });
        }
        // console.log(this.editData, "this.editData");
        this.selectDatas = arr.map((item) => {
          if (item.data.code !== 20000) {
            this.$message.error("出错了，请刷新页面重试");
          }
          return item.data.data;
        });
        // console.log(this.selectDatas);
      });
    } else {
      Promise.all([
        getDepartmentList(),
        getUsersList(),
        getProjectList(),
        getProducelist(),
        getTechnologyManager()
      ]).then((arr) => {
        // console.log(arr, "arr");
        this.selectDatas = arr.map((item) => {
          if (item.data.code !== 20000) {
            this.$message.error("出错了，请刷新页面重试");
          }
          return item.data.data;
          
        });
        this.form.setFieldsValue({
              department_id: userInfo.department_id,
              author_id:userInfo.user_id
            });
      });
    }
  },

  computed: {},
  methods: {
    // 文本编辑器内容改变时的回调函数被
    change(val) {
      console.log(val, 111);
      console.log(this.detail, 111);
    },
    handleSelectChange() {},
    handleSubmit() {
      this.form.validateFields((err, values) => {
        console.log(err, values);
        if (!err) {
          if (!this.$route.query.id) {
            add(values).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "提交成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              } else {
                this.$message.error(res.data.message || "提交异常，请重试~");
              }
            });
          } else {
            edit({
              ...this.editData,
              ...values,
              id: this.$route.query.id
            }).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "修改成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              } else {
                this.$message.success(res.data.message || "提交异常，请重试~");
              }
            });
          }
        }
      });
    },
    handleChange(info) {
      const status = info.file.status;
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (status === "done") {
        this.$message.success(`${info.file.name} 上传成功~`);
      } else if (status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    beforeUpload(file, fileList) {
      console.log(file, fileList);
      // console.log(this.form.getFieldValue("files"), 111);
      // if (fileList.length > 1) {
      //   this.$message.error("头像只能上传一张哦~");
      //   return false;
      // }
    },
    normFile(e) {
      console.log("Upload event:", e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    }
  }
};
</script>

<style lang="less" scoped>
</style>
